﻿using System.Collections.Generic;
using EnvDTE;

namespace AutoWrockTestable.Template
{
    public class TypeLoaderService
    {
        private readonly _DTE dte;

        public TypeLoaderService(_DTE dte)
        {
            this.dte = dte;
            Types = new HashSet<CodeElement>();
        }

        public ISet<CodeElement> Types { get; private set; }

        internal ISet<CodeElement> LoadTypes()
        {
            for(var i=1; i <= dte.Documents.Count; i++)
            {
                var doc = dte.Documents.Item(i);
                var projectItem = doc.ProjectItem;
                if(projectItem != null)
                {
                    var codeModel = projectItem.FileCodeModel;
                    if (codeModel != null)
                    {
                        for (var ii = 1; ii <= codeModel.CodeElements.Count; ii++)
                        {
                            var element = codeModel.CodeElements.Item(ii);
                            ExtractTypesFromCodeElement(element);
                        }
                    }
                }
            }
            return Types;
        }

        private void ExtractTypesFromCodeElement(CodeElement element)
        {
            if (element.Kind == vsCMElement.vsCMElementStruct || element.Kind == vsCMElement.vsCMElementClass)
                Types.Add(element);
            if(element.Children.Count > 0)
            {
                for (var i = 1; i <= element.Children.Count; i++)
                {
                    var child = element.Children.Item(i);
                    ExtractTypesFromCodeElement(child);
                }
            }
        }
    }
}
